import React from 'react'
import { info, success, DnD, IconFont, error, Switch, Select, Input, Modal, Checkbox, Button,Link, TitleBar, Table } from '../../ui-components'
import util from '../../util'
import { DATA_TYPE } from './constants'
import { MultiPick, Address, MultiFile, SingleFile, SinglePick, ShortText, LongText, DateTime } from './field-detail'
import { bindActionCreators } from 'redux'
import * as fieldAction from '../../actions/profileFieldDetail.action'
import { connect } from 'react-redux'
import style from './style.profileSettings'
import cx from 'classnames'
import {TemplateMap,getFieldGroup}  from '../../constants/fieldsMap'

export default
@connect(({app, profileTemplate, profileFieldDetail}) => ({app, profileTemplate, profileFieldDetail}), dispatch => ({actions: bindActionCreators(fieldAction, dispatch)}))
class ProfileSettings extends React.Component {

  state = {
    // 添加档案模板
    addProfileTemplate: 0,
    // 删除档案模板
    deleteProfileTemplate: 0,
		// 删除档案模板字段
		deleteProfileTemplateField: 0,
		// 添加档案模板字段面板
		addProfileTemplateFieldPanel: {},
		// 添加档案模板字段
		addProfileTemplateField: 0,
    // 新档案模板名称
    newProfileTemplateName: '',
		// 添加字段分组
		addProfileTemplateFieldContainer: 0,
		// 删除字段分组
		deleteProfileTemplateFieldContainer: 0,
		// 新建分组名称
		newProfileTemplateFieldContainerName: '',
		// container ui
		containerUi: {},
		// 只显示container
		onlyContainer: 0,
    // 更新分组名称
    editContainerName: false,
    readyEditContainer: {}
  }

  editFieldDisplayName = ''
  containerNewName = ''
  checkName = (name) => {
    const flag = !!name.match(/(\s|_)+/g);
    if(flag){
      error('字段内不能包含空格或下划线')
    }
    return flag;
  }
	toggleOnlyContainer() {
		this.setState({
			onlyContainer: 1-this.state.onlyContainer
		})
	}

	// toggle 字段选择模板
	// toggle fields列表显示
	updateContainerUi(profileFieldId, arg) {
		if (typeof arg === 'string') {
			arg = {
				[arg]: !(this.state.containerUi[profileFieldId] || {})[arg]
			}
		}
		this.setState({
			containerUi: {
				...this.state.containerUi,
				[profileFieldId]: {
					...this.state.containerUi[profileFieldId],
					...arg
				}
			}
		})
	}

	// 请求编辑字段
	requestEditProfileTemplateField(field) {
		const { typeSpec, ...others } = field
		const { pickOptions=[] } = typeSpec || {}
		let arg = {
			...others
		}
		if (pickOptions) {
      const options = pickOptions.filter(v => v.isDeprecated != 1);
			arg = {
				...arg,
        pickOptions: options
			}
		}
		this.props.actions.updateProfileTemplateFieldDetail(arg)
		this.requestAddOrUpdateProfileTemplateField(field.dataType, field.containerId, { update: true }, field.displayName)
	}
  requestEditProfileTemplateFieldCore(field) {
    this.props.actions.updateProfileTemplateFieldDetailCore(field)
    this.requestAddOrUpdateProfileTemplateField(field.dataType, field.containerId, { update: true }, field.displayName)
  }
	// 排序
	sortProfileTemplateField(data) {
		const { 
			from, 
			to, 
			profileFieldId, 
			dataType, 
			logicalIndex, 
			containerId 
		} = data

		this.props.sortProfileField({containerId, from: logicalIndex, to: logicalIndex+(to-from)})

    let arg = {
			profileFieldId,
			dataType,
			logicalIndex: logicalIndex+(to-from)
    }

    if (dataType != 1) {
      arg.containerId = containerId
    }

		this.props.reorderProfileField(arg)
	}

	// 添加字段分组
	addProfileTemplateFieldContainer() {
    if (util.isNull(this.editFieldDisplayName)) return error('分组名称不能为空!');
    if(this.checkName(this.editFieldDisplayName)) return;
    info('添加中...')
		this.props.addProfileField({
			displayName: this.editFieldDisplayName,
			dataType: 1,
			isSystemRequired: 0,
			isPublicVisible: 1,
			isEnabled: 1,
			isMandatory: 1
    }, () => {
      success('添加分组成功!')
      this.props.fetchProfileTemplateFields();
    })

    this.editFieldDisplayName = ''
		this.dialog('addProfileTemplateFieldContainer')
	}

  // toggle dialog
  dialog(name): void {
    this.setState({
      [name]: 1 - this.state[name]
    })
  }

	

	// 读取模板field列表
	fetchProfileTemplateFields() {
		this.props.fetchProfileTemplateFields()
	}

	// 更新field字段
	updateProfileTemplateField(args, flag) {
    if(flag) 
      this.props.updateProfileTemplateFieldCore(args,() => {
        success('更新字段成功!')
      });
    else 
      this.props.updateProfileTemplateField(args, () => {
        success('更新字段成功!')
      })
	}

	// 请求删除field字段
	requestDeleteProfileTemplateField(args, group) {
		this.setState({
			curField: args
		})
		if (group) {
			this.dialog('deleteProfileTemplateFieldContainer')
		} else {
			this.dialog('deleteProfileTemplateField')
		}
	}

	// 删除field字段
	deleteProfileTemplateField(group) {
    this.props.deleteProfileTemplateField(this.state.curField, () => {
      success(`删除${group === true? '分组':'字段'}成功!`)
    })
		if (group === true) {
			this.dialog('deleteProfileTemplateFieldContainer')
		} else {
			this.dialog('deleteProfileTemplateField')
		}
	}

	// toggle添加字段面板
	toggleAddProfileFieldPanel(profileFieldId) {
		this.setState({
			addProfileTemplateFieldPanel: {
				...this.state.addProfileTemplateFieldPanel,
				[profileFieldId]: !this.state.addProfileTemplateFieldPanel[profileFieldId]
			}
		})
	}

	// 添加或更新档案模板字段
	addOrUpdateProfileTemplateField() {
		const { requestAddProfileTemplateFieldDataType: dataType } = this.state
		const { pickOptions, profileFieldId, referenceName,containerId, ...others } = this.props.profileFieldDetail
		const { profileTemplateId } = this.props.location.query
		if (util.isNull(this.editFieldDisplayName)) return error('字段名称不能为空')
    if(this.checkName(this.editFieldDisplayName)) return;
		// 单选或双选
		if (dataType == 10 || dataType == 11)  {
			if (util.isNull(pickOptions)) return error('至少添加一个选项')
		}
		// 更新字段
		if (profileFieldId || referenceName) {
			let arg = {}
			if (dataType == 10 || dataType == 11) {
				arg = {
					typeSpec: {
            pickOptions: pickOptions.map((item, optionIndex) => {
              const { edit, ...others } = item
              return {
                ...others,
                optionIndex
              }
            })
          }
				}
			}
      if(others.isSystemRequired && others.isEdit) {

        arg = {
          pickOptions: pickOptions.map((item, optionIndex) => {
            const { edit, ...Itemothers } = item
            return {
              orgId: null,
              orgPickOptionId: null,
              isDeprecated: 0,
              ...Itemothers,
              optionIndex,
              configType: others.configType,
            }
          })
        }
      }
			const { 
				isMandatory, 
				isPublicVisible, 
				isEnabled, 
        //displayName
			} = this.props.profileFieldDetail

			arg = {
				...arg,
				isMandatory,
				isPublicVisible,
				isEnabled,
				displayName: this.editFieldDisplayName,
				dataType,
				profileTemplateId,
				profileFieldId,
        containerId,

			}
      if(!!this.props.profileFieldDetail.isSystemRequired)
        this.props.actions.updateJobField(arg,() => {
          this.editFieldDisplayName = ''
          success('更新字段成功!')
        })
      else
        this.props.updateProfileTemplateField(arg, () => {
          this.editFieldDisplayName = ''
          success('更新字段成功!')
        })
		}
		// 添加字段
		else {
			let arg = { 
				...others,
				dataType, 
        displayName: this.editFieldDisplayName,
				profileTemplateId,
				containerId: this.state.requestAddProfileTemplateFieldContainerId,
				isSystemRequired: 0
			}
			// 单选或双选
			if (dataType == 10 || dataType == 11)  {
				arg = {
					...arg,
					typeSpec: {
						pickOptions: pickOptions.map((item, i) => {
							const { edit, ...others } = item
							return {
								...others,
								optionIndex: i
							}
						})
					}
				}
			}
      this.props.addProfileField(arg, () => {
        this.editFieldDisplayName = ''
        this.props.fetchProfileTemplateFields()
        success('添加字段成功!')
      })
		}

		this.closeAddProfileTemplateFieldDialog()
	}

  requestEditContainerName(field) {
    this.setState({
      readyEditContainer: field,
      editContainerName: true
    })
  }

  cancelEditContainer() {
    this.containerNewName = ''
    this.setState({
      editContainerName: false,
      readyEditContainer: {}
    })
  }

  updateContainerName() {
    if (util.isNull(this.containerNewName)) return error('分组名称不能为空!')
    if(this.checkName(this.containerNewName)) return;
    this.props.updateProfileTemplateField({
      dataType: 1,
      displayName: this.containerNewName,
      profileFieldId: this.state.readyEditContainer.profileFieldId

    }, () => {
      success('更新分组名称成功!')
    })
    this.cancelEditContainer()
  }

	// 请求添加或更新档案模板字段
	requestAddOrUpdateProfileTemplateField(dataType, containerId, type, displayName) {
		this.setState({
			requestAddProfileTemplateFieldDataType: dataType,
			requestAddProfileTemplateFieldContainerId: containerId,
			requestUpdateProfileTemplateField: type && type.update,
			FIELD_DETAIL: (() => {
				switch(+dataType) {
					case 5:
						return ShortText
					case 4:
						return DateTime
					case 6:
						return LongText
					case 8:
						return Address
					case 10:
						return SinglePick
					case 11:
						return MultiPick
					case 13:
						return SingleFile
					case 14:
						return MultiFile
				}
			})()
		})
    this.editFieldDisplayName = displayName? displayName: ''
		this.dialog('addProfileTemplateField')
	}

	// 关闭对话框
	// 同时清除redux数据
	closeAddProfileTemplateFieldDialog() {
		this.dialog('addProfileTemplateField')
		setTimeout(() =>
			this.props.actions.clearProfileTemplateFieldDetail(),
			200
		)
	}

	componentWillReceiveProps(props) {

		// 拖拽成功
		if (!this.props.profileTemplate.reorder && props.profileTemplate.reorder) {
			// 重新fetch field列表
			props.fetchProfileTemplateFields()
		}


    const { list } = props.profileTemplate
    // 删除档案模板
    if (list.length < this.props.profileTemplate.list.length) {
      if (list.length) {
        let find
        find = list.filter(item => item.isPreset == 1)[0]
        if (!find) find = util.last(list)
        props.router.replace({
          pathname: props.location.pathname,
          query: {
            profileTemplateId: find.profileTemplateId
          }
        })
      }
    }

	}

  componentDidMount() {
    this.fetchProfileTemplateFields()
  }

  renderProfileTemplates(list) {
    if(util.isNull(list)) return null
    return (
      <div className={style.profileTemplates}>
        <div style={{width:'300px'}} >
          <Select 
  					value={this.props.location.query.profileTemplateId}
  					onChange={::this.changeProfileTemplate}
          >
            {
              list.map(({ displayName, profileTemplateId }, i) => (
                <option value={profileTemplateId} key={i}>{ displayName }</option>
              ))
            }
          </Select>
        </div>
        {/*
        <Link label={!this.state.onlyContainer? "分组排序": "取消分组排序"} onClick={::this.toggleOnlyContainer}/>*/}
      </div>
    )
  }

	renderProfileTemplateFields(props) {
    const { roleNameList=[] } = this.props.app.profile
		const { fields } = props

		if (util.isNull(fields)) return null
		const config = {
			model: {
				isEnabled: '启用', 
				displayName: '名称', 
				dataType: '文本类型', 
				isMandatory: '必填', 
				isPublicVisible: '显示', 
				others: '',
				drag: ''
			},
			//head: false,
			config: {
				isMandatory: .3,
				isPublicVisible: .6,
				isEnabled: .5,
				others: .5,
				drag: .1
			},
			map: {
        displayName: (v, item) => (
          <div>
            <span style={item.isEnabled? {}: { opacity: '.5' }}>{v}</span>
            {/*
              item.isSystemRequired?
              <span style={{ backgroundColor: '#CED8E2', marginLeft: '15px', width: '39px', height: '15px', color: '#F3F6F9', fontSize: '12px', lineHeight: '15px', display: 'inline-block', textAlign: 'center' }}>系统</span>
              : null
            */}
          </div>
        ),
				drag: (_, { isSystemRequired }) => {
					if (isSystemRequired) return null
					return <IconFont className={style.drag} value="drag"/>
				},
        dataType: (value, item) => <span style={item.isEnabled? {}: {opacity: '.5'}}>{ DATA_TYPE[value] }</span>,
				others: (_, args) => {
          if(args.isSystemRequired){
            if(args.isEdit)
              return (
                <div data-role="table-hover" className={style.edit}>
                  <Link className={style['edit-modify']} onClick={() => this.requestEditProfileTemplateFieldCore(args)}>编辑</Link>
                </div>
              )
            else 
              return null;
          }else 
  					return (
  						<div data-role="table-hover" className={style.edit}>
                {
                  !args.isSystemRequired?
  							  <Link color="red" onClick={() => this.requestDeleteProfileTemplateField(args)}>删除</Link>: null
                }
                {
                  args.isEnabled?
  							  <Link className={style['edit-modify']} onClick={() => this.requestEditProfileTemplateField(args)}>编辑</Link>: null
                }
  						</div>
  					)
				},
        isEnabled: (_, item) => {
          return (
            <Switch
              disabled={!item.isEnabledEditable}
              simple
              small
              onClick={() => {
                if (!item.isEnabledEditable) return
                this.updateProfileTemplateField({ 
                  profileFieldId: item.profileFieldId, 
                  dataType: item.dataType,  
                  //profileTemplateId: item.profileTemplateId, 
                  // toggle
                  referenceName: item.referenceName,
                  isEnabled: 1-item.isEnabled,
                  containerId: item.containerId,
                }, !!item.isSystemRequired)
              }}
              value={item.isEnabled}
            />
          )
        },
				...(() => {
					let obj = {};
					[
						'isPublicVisible,公开|保密', 
						'isMandatory,必填|选填'
					].forEach(item => {
						const [ name, pair ] = item.split(',')
						obj[name] = (_, v) => {
              if(name === 'isPublicVisible' && v.isSystemRequired) {
                return v.isActiveStaffEditable? 
                  <Link size="32" className={style['edit-icon']} icon={'tick'} />
                  :null
              };
              if(name === 'isMandatory'&& v.isSystemRequired) {
                return v.isMandatory? 
                  <Link size="32" className={style['edit-icon']} icon={'tick'} />
                  :null
              }
							const { profileFieldId, dataType, profileTemplateId, containerId } = v
							return (
								<Checkbox
									active={v[name]}
									disabled={!v.isEnabled || !v[`${name}Editable`]}
									onClick={
                    () => {
                      if (!v.isEnabled) return
                      if (!v[`${name}Editable`]) return
                      this.updateProfileTemplateField({ 
                        profileFieldId, 
                        dataType,  
                        profileTemplateId, 
                        containerId,
                        // toggle
                        [name]: 1-v[name] 
                      })
                    }
									}
								/>
							)
						}
					})
					return obj
				})()
			}
		}
		const hideTable = field => this.state.containerUi[field.profileFieldId] && this.state.containerUi[field.profileFieldId].fieldTable
		const showFieldPanel = field => this.state.containerUi[field.profileFieldId] && this.state.containerUi[field.profileFieldId].addProfileTemplateFieldPanel
		if (props.dragEnd) {
			this.sortProfileTemplateField({...props.fields[props.from], from:props.from, to: props.to})
		}
    let sysTitle = 0,
      otherTitle = 0;
		return (
			<div className={style.profileTemplateFields}>
				{  
					fields.map((field, i) => {
            const _config = {...config};
            if(field.isSystemRequired)
              _config.model = {
                ..._config.model,
                isPublicVisible: '员工是否可改',
              };
            if(field.isSystemRequired) 
              sysTitle++;
            else 
              otherTitle++;
            return (
              <div>
                {sysTitle===1? <h2 className={style['edit-header']}>{'系统字段'}</h2>: null}
                {otherTitle===1? <h2 className={style['edit-header']}>{'自定义字段'}</h2>: null}
    						<div draggable={!!this.state.onlyContainer} disabled={field.isSystemRequired} key={i}>
    							<h2>
    								<span>{ field.displayName }</span>
    								<div className={style['edit-container']}>
                      {!field.isSystemRequired?
                        <Link className={style['edit-container-modify']} onClick={() => this.requestEditContainerName(field)} icon="modify"/>:null
                      }
                      {!field.isSystemRequired?
    										<Link className={style['edit-container-remove']} icon="remove" onClick={() => this.requestDeleteProfileTemplateField(field, true)}/>: null
                      }
    									{
    										(!field.isSystemRequired && this.state.onlyContainer)?
    										<IconFont className={style.drag} value="drag"/>: null
    									}
    								</div>
    							</h2>
    							{
    								!this.state.onlyContainer?
    								<Table 
    									sortUpdate={::this.sortProfileTemplateField}
    									sortable={field => !field.isSystemRequired}
    									data={field.children? (field.children.length? field.children.filter(v => ~v.dataType): null): null}
    									{..._config}
    								/>: null
    							}
    							{
    								!this.state.onlyContainer && !field.isSystemRequired ? 
    							<Link 
    								icon="plus" 
    								color="blue" 
    								label="添加字段" 
    								onClick={() => this.updateContainerUi(field.profileFieldId, 'addProfileTemplateFieldPanel')} 
    								className={style.addProfileTemplateField}/>: null
    							}
    							{
    								(showFieldPanel(field) && !this.state.onlyContainer)?
    								<ul className={style.addProfileTemplateFieldPanel}>
    									{
    										['5', '4', '6', '8', '10', '11', '13', '14'].map((type, i) => (
    											<li key={i}>
    												<Link onClick={() => this.requestAddOrUpdateProfileTemplateField(type, field.profileFieldId)} label={DATA_TYPE[type]}/>
    											</li>
    										))
    									}
    								</ul>: null
    							}
    						</div>
              </div>

  					)
          })
				}
			</div>
		)
	}

  render() {
    const { list, fieldMap } = this.props.profileTemplate
		const fields = getFieldGroup(TemplateMap, fieldMap) || [];
		const SortableContainer = DnD({ignored: '[disabled]'})(this.renderProfileTemplateFields.bind(this))
    return (
      <div>
        {/** Title Bar **/}
        {/** 新建档案模板入口 **/}
        <TitleBar 
          label="花名册字段设置"
          //add={{ label: '新建模板', handler: () => this.dialog('addProfileTemplate') }}
        />
        { /*this.renderProfileTemplates(list) */}
				{
					fields.length?
					<SortableContainer fields={fields}/>: null
				}
        {
          !fields.some((v) => !v.isSystemRequired)
          ? <h2 style={{margin: '30px 0 0'}} className={style['edit-header']}>{'自定义字段'}</h2> : null
        }
				<div className={style.foot}>
					<Link onClick={() => this.dialog('addProfileTemplateFieldContainer')} size="14" label="添加字段分组" />
					{/*
            <Link onClick={() => this.dialog('deleteProfileTemplate')} size="14" label="删除模板" icon="delete"/>
          */}
				</div>

        {/** 删除档案模板字段Dialog  **/}
        <Modal
          active={this.state.deleteProfileTemplateField}
          onRequestClose={() => this.dialog('deleteProfileTemplateField')}
          actions={[ 'cancel', ::this.deleteProfileTemplateField ]}
          title="删除档案模板字段"
        >
					<div>
						<p>确定删除<b>`{ this.state.curField && this.state.curField.displayName }`</b>字段吗?</p>
					</div>
        </Modal>
        {/** 添加档案模板字段Dialog  **/}
        <Modal
					twoColumn
          active={this.state.addProfileTemplateField}
          onRequestClose={::this.closeAddProfileTemplateFieldDialog}
					actions={['cancel', { label: this.state.requestUpdateProfileTemplateField? '更新': '确定', handler: ::this.addOrUpdateProfileTemplateField }]}
        >
					<div>
						<div>
							<div data-role="dialog-title">
								{ DATA_TYPE[this.state.requestAddProfileTemplateFieldDataType] }
							</div>
							{
                this.state.FIELD_DETAIL? <this.state.FIELD_DETAIL.Edit {...this.props.actions} {...this.props.profileFieldDetail} editFieldDisplayName={this.editFieldDisplayName} updateProfileTemplateFieldTitle={v => { this.editFieldDisplayName = v.displayName }}/>: null
							}
						</div>
						<div>
							<div data-role="dialog-title">预览</div>
							{
								this.state.FIELD_DETAIL? <this.state.FIELD_DETAIL.Preview {...this.props.profileFieldDetail} labelValue={this.editFieldDisplayName}/>: null
							}
						</div>
					</div>
        </Modal>
        {/** 新建字段分组Dialog  **/}
        <Modal
          active={this.state.addProfileTemplateFieldContainer}
          onRequestClose={() => this.dialog('addProfileTemplateFieldContainer')}
          actions={['cancel', ::this.addProfileTemplateFieldContainer ]}
          title="添加字段分组"
        >
					<div>
						<Input 
              onChange={ e => { this.editFieldDisplayName = e.target.value } }
							autoFocus 
							label="分组名称"/>
					</div>
        </Modal>
        {/** 删除字段分组Dialog  **/}
        <Modal
          active={this.state.deleteProfileTemplateFieldContainer}
          onRequestClose={() => this.dialog('deleteProfileTemplateFieldContainer')}
          actions={['cancel', () => this.deleteProfileTemplateField(true)]}
          title="删除字段分组"
        >
					<p>确定删除<b>`{ this.state.curField && this.state.curField.displayName }`</b> 分组吗?</p>
        </Modal>
        {/** 编辑字段分组名称Dialog  **/}
        <Modal
          active={this.state.editContainerName}
          onRequestClose={::this.cancelEditContainer}
          actions={['cancel', ::this.updateContainerName]}
          title="更新分组名称"
        >
          <div>
            <Input
              autoFocus
              label="分组名称"
              onChange={e => { this.containerNewName = e.target.value }}
              defaultValue = {this.state.readyEditContainer.displayName}
            />
          </div>
        </Modal>
      </div>
    )
  }
}
